/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.core;

import org.lt.cj.config.entities.ConfigModel;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.lt.cj.core.server.ServerModel;
import org.lt.cj.core.server.entity.ResponseMassege;
import org.lt.cj.core.utils.CommandList;

/**
 * 任务管理器，最高组织者
 * @author luohong
 */
public class TaskManager {

    private ConfigModel configModel;                                            //这东西相当于任务书，执行者是TaskImpl
    private Task task;                                                          //任务接口，负责接收任务
    private Set<String> taskNameList = new HashSet<String>();                   //存储任务列表
    private Map<String, Task> taskList = new HashMap<String, Task>();           //HashMap存储任务列表
    private static TaskManager instance = new TaskManager();
    private ServerModel serverModel = ServerModel.getInstance();

    private TaskManager() {                                                    //总经理位置，不许随便构造
    }

    public static TaskManager getInstance() {                                 //获取任务管理器实例

        if (instance == null) {
            instance = new TaskManager();
        }
        return instance;
    }

    private void initTaskPaper(ConfigModel configModel) {
        this.configModel = configModel;                                         //接收任务书
        task = new TaskImpl(configModel);                                       //创建任务执行者

    }

    private void setTaskImplName() {                                          //为任务命名，也是在线程组命名

        String taskName = configModel.getTaskName();                            //取得配置文件的任务命名
        if (taskNameList.contains(taskName)) {
            Iterator ir = taskNameList.iterator();
            int i = 0;
            boolean falg = true;                                                //定义一个循环标志
            while (falg) {                                                      //将任务重命名，并循环检查是否有仍重名
                String temp = taskName + i;
                if (!taskNameList.contains(temp)) {
                    task.setTaskName(taskName);                                 //设置任务名称
                    taskNameList.add(taskName);                                 //任务名列表里添加任务名
                    configModel.setTaskName(taskName);
                    taskList.put(taskName, task);                               //设置任务和任务执行者的映射关系
                    falg = false;
                }
            }
        } else {
            task.setTaskName(taskName);                                         //设置任务名称
            taskNameList.add(taskName);                                         //任务名列表里添加任务名
            configModel.setTaskName(taskName);
            taskList.put(taskName, task);                                       //设置任务和任务执行者的映射关系
        }
    }

    private void startNewTask() {

        task.processTask();
        //用钩子把任务挂起来，在退出程序的时候
//        ShutdHookThread thread = new ShutdHookThread(task);
//        Runtime.getRuntime().addShutdownHook(thread);
    }

    public ResponseMassege getTasksState() {                                  //获取任务状态信息

        ResponseMassege msg = new ResponseMassege();
        Iterator it = taskList.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Task> entry = (Map.Entry<String, Task>) it.next();
            Task taskObject = entry.getValue();
            msg.getTaskStateList().add(taskObject.getTaskState());
            //to do  在这里添加各个任务的状态信息
        }
        return msg;
    }

    public String sendCommand(String command, String taskName) {              //向服务器端发送命令的接口方法，包括终止任务，暂停以及停止任务
        String responseMsg = "";
        Iterator it = taskList.entrySet().iterator();
        if (command.trim().equals(CommandList.stopAllCommand)) {
            while (it.hasNext()) {
                Map.Entry<String, Task> entry = (Map.Entry<String, Task>) it.next();
                Task taskObject = entry.getValue();
                responseMsg = taskObject.takeOrder(CommandList.stopCommand);
            }
            return responseMsg;
        }
        while (it.hasNext()) {

            Map.Entry<String, Task> entry = (Map.Entry<String, Task>) it.next();
            Task taskObject = entry.getValue();
            if (entry.getKey().equals(taskName.trim())) {
                responseMsg = taskObject.takeOrder(command);
            }
        }
        return responseMsg;
    }

    public void acceptNewTask(ConfigModel configModel) {                      //接收任务书

        initTaskPaper(configModel);                                             //初始化任务书
        serverModel.saveTask(configModel);                                      //保存该任务实例，创建实例对应的文件
        setTaskImplName();                                                      //设置任务名并保存在案
        startNewTask();                                                         //开始新任务
    }

    public void loadOldTask(ConfigModel configModel) {                         //重新加载以前的任务书

        initTaskPaper(configModel);                                             //初始化任务书
        setTaskImplName();                                                      //设置任务名并保存在案
        startNewTask();                                                         //开始新任务
    }

    public void reloadTasks() {

        ConfigModel[] tasks = serverModel.loadTasks();
        if (tasks != null) {
            for (int i = 0; i < tasks.length; i++) {
                if (tasks[i] != null) {
                    loadOldTask(tasks[i]);
                }
            }
        }
    }

//    public void shutDownService() {
//
//        Iterator it = taskList.entrySet().iterator();
//        while (it.hasNext()) {
//
//            Map.Entry<String, Task> entry = (Map.Entry<String, Task>) it.next();
//            Task taskObject = entry.getValue();
//            ShutdHookThread thread = new ShutdHookThread(taskObject.getConfigModel(), taskObject.getLinkDB());
//            Runtime.getRuntime().addShutdownHook(thread);
//        }
//    }
    public static void main(String[] args) {
    }
}
